<template>
<div>
    <div class="e-form">
        <div class="tabs warningTabs">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="结算明细" name="changeDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="服务费用" name="recommendedLessor" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="保证金" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
            <el-form ref="form" :model="formData" label-width="160px" :rules="rules">

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算编号：">
                            {{formData.billNo }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构：" prop="orgName">
                            <span>{{ formData.orgName }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务类型：">
                            <span>{{formData.businessTypeValue}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="源单编号：">
                            <span>{{formData.sourceNo }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算单位：" >
                            <span>{{formData.settleOrg}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算类型：">
                            <span>{{formData.settleType }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发票号：" >
                            <span>{{formData.invoiceNo }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="录入人员：" v-model='formData.inputName'>
                            <span>{{formData.inputName}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="不含税金额(元)：" >
                            <span>
                                {{formData.taxExcluding}}
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算日期：" :disabled="true" prop='settleDate'>
                            <span>{{formData.settleDate}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税率：" >
                            <span>
                                {{formData.taxRate}}
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="税价合计：">
                            <span>{{ formData.totalTaxPrice }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税额：" >
                           <span>
                               {{formData.taxAmount}}
                           </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="累计结算金额：">
                            <span>{{ formData.cumulativeSettleAmount }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="服务单位费用(含税，元)：" >
                            <span>
                                {{formData.transportUnitCost}}
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单据来源：">
                            <span>{{ formData.billSource }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲预付款金额(元)：" prop='advanceChargeAmount'>
                            <el-checkbox v-model="checkedBox"  :disabled="true" ></el-checkbox>
                            <span>
                                {{formData.advanceChargeAmount}}
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="验收编号：">
                            <span>{{ formData.acceptanceNo }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支：" v-model="checkPerson">
                            <el-checkbox :disabled="true" ></el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="终期结算：">
                            <el-checkbox v-model="formData.isFinalSettle" :disabled="true" ></el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支金额(元)：" >
                            <span>
                                {{formData.rushPersonalBorrowingAmount}}
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="币种：">
                            <span>
                                {{formData.currency}}
                            </span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲销对象：" >
                           <el-select
                                v-model="formData.reversalObjectName"
                                placeholder="请选择"
                                 @change="settleOrgChange"
                            >
                                 <el-option
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态：" >
                            {{shuziShow(formData.state)}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借支人员：" >
                            <span>{{ formData.borrower}}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算金额(本位币)：">
                            <span>{{  formData.settleAmount}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：" >
                            <!-- <el-input placeholder="" v-model="input3" class="input-with-select" type="textarea"
                            :rows="3" style='border:0'> -->
                            <span>
                                {{formData.remarks}}
                            </span>
                            <!-- </el-input> -->
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <!-- 仅发生冲红单业务时,才显示该字段,暂未做判断 -->
                        <el-form-item label="冲红单:">
                            <div :style="redBillStateStyle">{{ redBillStateFun(formData.redStatus) }}</div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="传输财务共享：">
                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.transferFinancialShare)}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

                        </div>
                    </div>

                    <div id="changeDetailCon" class="con">
                        <div class="tabs-title" id="changeDetail">结算明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button size="mini" class="btn-blue" @click="selectEquip">选择物资</el-button>
                                        <el-button size="mini" class="btn-delete" @click="deletePlanList">删除</el-button>
                                    </div>
                                </div>
                                <div class="right">
                                    合计：
                                </div>
                            </div>
                           <div class="e-table">
                            <el-table
                                :data="acceptanceData"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :row-class-name="tableRowClassName"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                            >
                                <el-table-column
                                    type="selection"
                                    width="55">
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassId"
                                    label="物资类别"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="150"
                                    @change="handleSelectEquip(row,$index)"

                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格"   min-width="150">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质"  min-width="150">
                                </el-table-column>
                                <el-table-column prop="unit" label="计量单位"  min-width="150">
                                </el-table-column>
                                <el-table-column
                                    label="未结算数量"
                                    min-width="150"
                                    prop="unsettleQuantity"
                                >
                                </el-table-column>
                                 <el-table-column
                                    label="结算数量"
                                    min-width="150"
                                    prop="quantity"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="验收单价（元）"
                                    min-width="150"
                                >
                                </el-table-column>
                                 <el-table-column
                                    label="结算单价（元）"
                                    min-width="120"
                                    prop="settlePrice"
                                    @blur="onQuantity(row)"
                                >
                                <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.settlePrice"
                                        placeholder="请输入结算单价"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="不含税金额（元）"
                                    min-width="150"
                                    prop="taxExcludedAmount"
                                >
                                <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.taxExcludedAmount"
                                        placeholder="请输入不含税金额"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                 <el-table-column
                                    label="差额（元）"
                                    min-width="150"
                                    prop="difference"
                                >
                                </el-table-column>
                                 <el-table-column
                                    label="税额差额（元）"
                                    min-width="150"
                                    prop="taxAmountDifference"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                            <!-- <div style="display: flex">
                            <div class="left">
                                <ComTreeFile />
                            </div>
                            <div class="right" style="margin-left: 20px; width: 100%">
                                <ComTreeTable />
                            </div>
                            </div> -->
                        </div>
                    </div>

                    <div id="recommendedLessorCon" class="con">
                        <div class="tabs-title" id="recommendedLessor">服务费用</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button size="mini" class="btn-blue" @click="newRentalBusiness">新增</el-button>
                                        <el-button size="mini" class="btn-delete" @click="deleteRentalBusiness">删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                class="table"
                                ref="recommendedLessor"
                                :data="rentalBusinessCopy"
                                border
                                @selection-change="rentalTableSelect"
                                :row-class-name="tableRowRental"
                            >
                              <el-table-column
                                    type="selection"
                                    width="55"
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    align="left"
                                    label="服务结算单位"
                                    min-width="200"
                                    show-overflow-tooltip
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="contractNumber"
                                    label="合同编号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <!-- 待修改 -->
                                <el-table-column
                                    prop="invoiceNo"
                                    label="发票编号"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="contractDtlName"
                                    label="清单名称"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.contractDtlName"
                                        placeholder="请输入清单名称"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="quantity"
                                    label="数量"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.quantity"
                                        placeholder="请输入数量"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.price"
                                        placeholder="请输入单价"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="taxRate"
                                    label="税率 % "
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.taxRate"
                                        placeholder="请输入税率"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="taxAmount"
                                    label="税额（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="{row}">
                                    <el-input
                                        v-model="row.taxAmount"
                                        placeholder="请输入税额"
                                        size="mini"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="totalAmount"
                                    label="税价合计（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="attach">保证金</div>
                        <div class="e-table">
                            <div class="tabs-title" id="attach">暂扣保证金</div>
                            <div>
                                <div class="left">
                                    <div>
                                        <el-button size="mini" class="btn-blue" @click="BoxHandelkou">添加</el-button>
                                        <el-button size="small" class="btn-delete" @click="handleChangeHistory">删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                class="table"
                                :data="changeKouTable"
                                border
                                ref="changeHistorySelect"
                                @selection-change="KouTableSelect"
                            >
                              <el-table-column
                                    type="selection"
                                    width="55"
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    align="left"
                                    label="名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="暂扣保证金（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="{row}">
                                    <el-input
                                        v-model="row.amount"
                                        placeholder="请输入暂扣保证金（元）"
                                        size="small"
                                        @input="curStateChange(row)"
                                    ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amountBqm"
                                    label="截至上期末暂扣保证金（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="{row}">
                                        <el-input
                                            v-model="row.amountBqm"
                                            placeholder="请输入截至上期末暂扣保证金（元）"
                                            size="small"
                                        @input="curStateChange(row)"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amountSqm"
                                    label="截至本期末暂扣保证金（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                  <template slot-scope = {row}>
                                        {{Math.ceil(((row.amountBqm)*100 + (row.amount)*100) / 100)}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="remarks"
                                    label="说明"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                             <div class="tabs-title" id="attach">返还保证金</div>
                            <div>
                                <div class="left">
                                    <div>
                                        <el-button size="mini" class="btn-blue" @click="boxHandelReturn">添加</el-button>
                                        <el-button size="small" class="btn-delete" @click="handleChangeHistory">删除</el-button>
                                    </div>
                                </div>
                            </div>
                            <el-table
                                class="table"
                                :data="changeReturnTable"
                                border
                                ref="changeHistorySelect"
                                @selection-change="changeHistoryTableSelect"
                                :row-class-name="tableRowRental"
                            >
                              <el-table-column
                                    type="selection"
                                    width="55"
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="returnDepositName"
                                    align="left"
                                    label="名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    fixed
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amountBqm"
                                    label="截至上期末未返还保证金（元）"
                                    min-width="300"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                  <template slot-scope="{row}">
                                        <el-input
                                            v-model="row.amountBqm"
                                            placeholder="请输入返还保证金（元）"
                                            size="small"
                                        @input="curStateChange(row)"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="返还保证金（元）"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope="{row}">
                                        <el-input
                                            v-model="row.amount"
                                            placeholder="请输入返还保证金（元）"
                                            size="small"
                                        @input="curStateChange(row)"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amountSqm"
                                    label="截至本期末未返还保证金（元）"
                                    min-width="300"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                 <template slot-scope = {row}>
                                        {{row.amountBqm - row.amount}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="remarks"
                                    label="说明"
                                    min-width="150"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="changeHistory">附件信息</div>
                        <attach-index :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                             <ComAuditHistoryIndex
                                billType=6095
                                ref="AuditHistoryRef"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
            <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
            <div class="buttons">
                <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
               <el-button
                    type="primary"
                    class="btn-blue"
                    @click="printHandel"
                    size="small"
                    v-debounce
                    v-if="state === '审核中' || state === '已审核'"
                    >打印</el-button
                >
                <el-button
                    type="primary"
                    class="btn-blue"
                    @click="printHandel"
                    size="small"
                    v-debounce
                    v-if="state === 1 || state === 2"
                    >关闭</el-button
                >
                <el-button
                    type="primary"
                    class="btn-blue"
                    @click="redHandel"
                    size="small"
                    v-debounce
                    v-if='formData.redStatus == null || formData.redStatus == ""'
                    >冲红单
                    </el-button
                >
                <PccExaButtons :auditState="auditState" @exas="exas" v-if="state !== 0" />
                <el-button size="small" @click="handleClose"  v-debounce>取消</el-button>
            </div>
         </div>
    </div>
</div>

</template>

<script>
import { mapState, mapMutations } from 'vuex'
import request from '@/api/PCCset/apply.js'
import '@/utils/jquery.scrollTo.min'
import attachIndex from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { openAppClient, hideLoading, selectDataClient, throttle, formatDate } from '@/utils/common'
import { getRmbRate, audit, commit, undoworkt, nullify, PccSetgetCurrentUnitInfo, PccgetAuditHistoryInfo } from '@/api/PCCset/common.js'
import { getUuid } from '@/utils/common'
import PccExaButtons from '@/components/common/exaButtons.vue'
// import count from '@/api/equip/equipPlanCount.js'
export default {
    data () {
        return {
            isFontColor: true,
            checkedBox: false,
            fake: true,    //判断changeType的数值  -1 1 2
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center',
            },
            auditHistoryTable: [], //审核历史表格
            SetFinalSettle: false,
            optionssettleOrg: [{         //冲销对象
                valuesettleOrg: '1',
                label: '结算单位',
            }, {
                valuesettleOrg: '2',
                label: '服务服务单位'
            }],
            changeKouTable: [],            //暂扣保证金
            changeReturnTable: [],      //返还保证金
            businessDtlLists: [{         //业务类型
                value: '1',
                label: '临时需用计划',
            }, {
                value: '2',
                label: '物资采购合同'
            }, {
                value: '3',
                label: '调拨单'
            }],
            value: '',
            errorAcceptanceMsg: [], // 结算明细
            visibleNewPlan: false,           //结算单位页面
            dtlList: [
                {
                    'amount': 0,
                    'amountBqm': 0,
                    'amountSqm': 0,
                    'billId': '',
                    'changeType': 0,
                    'dtlId': '',
                    'remarks': '',
                    'returnDepositId': '',
                    'returnDepositName': '',
                    'returnDepositType': 0
                }
            ],
            tableDataReturnList: [],      //返还保证金
            tableDataList: [],   // 暂扣金额数据
            visibleKou: false,
            visibleReturn: false,
            isBatch: [
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                },
                {
                    flag: false,
                    batch: '进入批量管理'
                }
            ],
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            tableData: [],
            ProcurementPlanVisible: false, //控制选择维修计划页面显示隐藏
            isRedSingle: false,
            formData: {
                //配置计划基础信息
                'acceptanceNo': '',
                'advanceChargeAmount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'billSource': 0,
                'borrower': '',
                'businessTypeKey': 0,
                'businessTypeValue': '',
                'cumulativeSettleAmount': 0,
                'currency': '',
                'currencyId': '',
                'evaluationGrade': 0,
                'inputId': '',
                'inputName': '',
                'invoiceNo': '',
                'isFinalSettle': 0,
                'isRed': 0,
                'isRushAdvanceCharge': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDesciption': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'redStatus': 0,
                'remarks': '',
                'reversalObjectId': 0,
                'reversalObjectName': 0,
                'rmbAmount': 0,
                'rmbRate': 0,
                'rushPersonalBorrowing': 0,
                'rushPersonalBorrowingAmount': 0,
                'settleDate': formatDate(new Date(), 'yyyy-MM-dd'), //结算日期,
                'settleOrg': '',
                'settleOrgId': '',
                'settleType': 0,
                'sourceId': '',
                'sourceNo': '',
                'state': 0,
                'taxAmount': 0,
                'taxExcluding': 0,
                'taxRate': 0,
                'totalTaxPrice': 0,
                'transferFinancialShare': 0,
                'transportUnitCost': 0,
                'workId': '',
                'settleAmount': 0
            },
            jiesuanmingxi:
                [{
                    'children': [
                        {
                            'billId': '',
                            'changeType': 0,
                            'difference': 0,
                            'dtlId': '',
                            'materialClassId': '',
                            'materialClassName': '',
                            'materialId': '',
                            'materialName': '',
                            'price': 0,
                            'quantity': 0,
                            'settlePrice': 0,
                            'spec': '',
                            'taxAmountDifference': 0,
                            'taxExcludedAmount': 0,
                            'texture': '',
                            'unit': '',
                            'unsettleQuantity': 0
                        }
                    ],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0
                }],
            yunshuAmount: [   //服务费用明细
                {
                    'amount': 0,
                    'billId': '',
                    'changeType': 0,
                    'contractDtlId': '',
                    'contractDtlName': '',
                    'contractId': '',
                    'contractNumber': '',
                    'dtlId': '',
                    'price': 0,
                    'quantity': 0,
                    'settlementUnitId': '',
                    'settlementUnitName': '',
                    'taxAmount': 0,
                    'taxRate': 0,
                    'totalAmount': 0
                }
            ],

            //主体信息表单数据    修改为弹框信息
            mainInfo: {
                notarization: {
                    'accountNumber': '',
                    'bankName': '',
                    'billId': '',
                    'name': '',
                    'notaryTime': null,
                    'opinion': '',
                    'sourceId': this.$route.query.billid,
                },
            },

            planConfigurationDtlList: [],          //结算明顯
            // planConfigurationDtlListCopy: [],    //结算明细
            acceptanceData: [],                 //选择物资 结算明细
            acceptanceCkeck: [],                 //结算明细选择项
            planSelect: [], //计划明细选择项
            currentRowPlan: {}, //计划明细当前行数据
            rentalBusinessCopy: [], //  服务费用
            rentalBusinesscheck: [], //  服务费用选择项
            rentalSelect: [], //推荐租赁商选择项
            currentRowRental: {}, //推荐租赁商当前行数据
            changeHistoryTable: [], //变更历史表格
            changeHistorySelect: [], //变更历史选择项
            changeReturnSelect: [],   //获取返还保证金选项数据
            changeKouSelect: [],   //获取暂扣保证金选项
            oldPccPlan: [], //从结算明细带过来的数据
            billId: this.$route.query.billId,
            billid: this.$route.query.billId,
            // userId: '',
            rules: {
                advanceChargeAmount: [
                    { required: true, message: '请填写冲预付款金额为必填项', trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '请填写机构名称', trigger: 'blur' }
                ],
                businessTypeValue: [
                    { required: true, message: '请选择业务类型', trigger: 'change' }
                ],
                settleDate: [
                    { required: true, message: '请选择结算日期', trigger: 'blur' }
                ],
                settleOrg: [
                    { required: true, message: '请选择冲销对象', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                billSource: [
                    { required: true, message: '请填写单据来源', trigger: 'blur' }
                ],
                invoiceNo: [
                    { required: true, message: '请填写发票号', trigger: 'blur' }
                ],
                remarks: [
                    { max: 500, message: '长度不超过500个字符', trigger: 'blur' }
                ],
            },
            checkPerson: false,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 6095,
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6095,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            oldConfigPlan: [], //从配置计划带过来的数据
            oldLeasePlan: [], //从选择物资带过来的数据
            winEvent: {},
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //当前单据状态
        state () {
            return this.formData.state
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 258 - this.lastConHeight
        },

    },
    components: {
        attachIndex,
        ComAuditHistoryIndex,
        PccExaButtons
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        //冲红单
        'formData.redStatus' () {
            if (this.formData.redStatus == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redStatus == '0' ||
                this.formData.redStatus == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redStatus == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
    },
    created () {
        this.formData.inputName = localStorage.getItem('userName')
        // this.getDicValue()
        this.billid = this.$route.query.billid
        this.userId = localStorage.getItem('userId')
        // this.getPlanList() // 结算明细表格数据
        const { baseCyByOrgId } = this.userInfo

        this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
        this.formData.baseCurName = baseCyByOrgId.currency
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'changeDetail', 'recommendedLessor', 'attach', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth
        this.screenHeight = document.documentElement.clientHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        this.scorllDtl()
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        //如果是-1就隐藏
        tableRowRental ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //状态红单
        redBillStateFun (redStatus) {
            if(redStatus == 1) {
                return '冲销中'
            }else if(redStatus == 2) {
                return '已冲销'
            }else if(redStatus == 3) {
                return '红单'
            }else if(redStatus == -1) {
                return '未冲销'
            }
        },
        //状态数字转换
        shuziShow (state) {
            if(state == -1) {
                return '已删除'
            }else if(state == 0) {
                return '草稿'
            }else if(state == 1) {
                return '审核中'
            }else if(state == 2) {
                return '已审核'
            }else if(state == 5) {
                return '已作废'
            }
        },
        //刷新历史审核列表
        getAuditHistory () {
            PccgetAuditHistoryInfo(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //币种切换
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.formData.currency === '人民币') {
                this.formData.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.formData.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.formData.currency === this.formData.baseCurName) {
                //币种=本位币
                this.formData.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.formData.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        ...mapMutations(['setSelectedInfo']),
        //终期结算
        checkToF () {
            console.log(111)
            if(this.setFinalSettle == true) {
                console.log(this.setFinalSettle)
                this.formData.isFinalSettle == 1
                console.log(this.formData.isFinalSettle)
            }else{
                this.formData.isFinalSettle == 0
            }
        },
        //金额类数据  1、税价合计   2、税额
        taxRateHandel (e) {
            console.log(e)
            if(0 <= e && e < 100) {
                this.formData.taxRate = e + '%'
                // this.formData.taxRate = e
                if(this.formData.taxExcluding && parseInt(this.formData.taxRate)) {
                    this.formData.taxAmount = ( parseInt(this.formData.taxRate) * this.formData.taxExcluding) / 100
                }
            }else{
                this.$message.error('税率填写范围为0~100')
            }
        },
        amountExcludingTaxHandel (e) {
            //不含税金额
            this.formData.taxExcluding = e
            if(this.formData.taxExcluding &&  parseInt(this.formData.taxRate)) {
                this.formData.taxAmount = ( parseInt(this.formData.taxRate) * this.formData.taxExcluding) / 100
            }
        },
        contractAmount (e) {
            // 税额
            this.formData.taxAmount = e
            if (this.formData.taxExcluding && this.formData.taxAmount || this.formData.advanceChargeAmount) {
                this.formData.totalTaxPrice = Math.ceil(parseInt((this.formData.taxExcluding) + parseInt(this.formData.taxAmount) + parseInt(this.formData.advanceChargeAmount)) * 100) / 100   //税价合计
                this.formData.taxAmount = Math.ceil(this.formData.taxAmount * this.formData.taxExcluding) * 100 / 100
            }
        },
        advanceChargeAmountHandel (e) {
            //冲预付款金额
            this.formData.advanceChargeAmount = e
            if (this.formData.taxExcluding && this.formData.taxAmount || this.formData.advanceChargeAmount) {
                this.formData.totalTaxPrice = Math.ceil(parseInt((this.formData.taxExcluding) + parseInt(this.formData.taxAmount) + parseInt(this.formData.advanceChargeAmount)) * 100) / 100   //税价合计
            }
        },
        transportUnitCostHandel (e) {
            //服务费用
            this.formData.transportUnitCost = e
            this.formData.cumulativeSettleAmount = Math.ceil(this.formData.totalTaxPrice + parseInt(this.formData.transportUnitCost)) * 100 / 100
        },
        //选择业务类型
        busTypeChange () {
            const findObj = this.businessDtlLists.find(item => item.value === String(this.formData.businessTypeKey))
            this.formData.businessTypeValue = findObj.label
        },

        // ------------------------------结算明细---------------------------------------
        //结算数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },

        // 监听结算数量
        acceptanceQuantityBlur (row) {
            row.changeType = 2
            if (
                row.notAcceptedQuantity &&
                row.acceptanceQuantity > row.notAcceptedQuantity
            ) {
                row.acceptanceQuantity = ''
                row.price = 0
            } else {
                if (!!row.acceptanceAmount && !!row.acceptanceQuantity) {
                    row.price = +row.acceptanceAmount / +row.acceptanceQuantity
                }
            }
        },

        // 监听结算金额
        acceptanceAmountBlur (row) {
            row.changeType = 2
            row.price = +row.acceptanceAmount / +row.acceptanceQuantity
        },

        //删除结算明细
        acceptanceDelete (row) {
            row.changeType = -1
        },
        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        // ------------------------------结算明细---------------------------------------
        amountWriter (row, e) {
            console.log(e)
            row.amount = e
            if (row.amount && row.amountBqm) {
                this.amountSqm = (parseInt(row.amount) + parseInt(row.amountBqm )).toFixed(2)
            }
        },
        settlePriceWrite (row, e) {
            row.amountBqm = e
            if (row.amount && row.amountBqm) {
                this.amountSqm = (parseInt(row.amount) + parseInt(row.amountBqm )).toFixed(2)
            }
        },
        ...mapMutations([ 'setAuditParams']),
        //获取当前使用的字典
        // getDicValue () {
        //     this.$store.dispatch('equip/setTimeUnitList')
        // },
        //传输财务共享字体颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
        shareFontColor () {
            if(this.formData.transferFinancialShare === 0 || this.formData.transferFinancialShare === 1) {
                this.isFontColor = true
            }else{
                this.isFontColor = false
            }
        },
        //去变更新增页面
        handleChange () {
            const billid = this.billid
            this.$router.push({
                path: '/NewPlanAdd',
                query: { billid }
            })
        },
        //去变更编辑页面
        tableEdit (billid) {
            this.$router.push({
                path: '/NewPlanDetail',
                query: { billid }
            })
        },
        //变更查看页面
        // tableDbShow (row) {
        //     // this.$router.push({
        //     //     path: '/leasePlanChangeShow',
        //     //     query: { billid: row.billId }
        //     // })
        //     this.auditParams.billId = row.billId
        //     PccSetgetCurrentUnitInfo(this.auditParams).then(res => {
        //         this.auditState = res
        //         if( this.auditState.canModify == true) {
        //             this.$router.push({
        //                 path: '/NewPlanDetail',
        //                 query: { billid: row.billId }
        //             })
        //         }else{
        //             this.$router.push({
        //                 path: '/NewPlanShow',
        //                 query: { billid: row.billId }
        //             })
        //         }
        //     })
        // },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                // this.getChangeHistory(),
                this.getAuditHistory(),
                this.PccSetgetCurrentUnitInfo(),  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        // //刷新历史审核列表
        // getAuditHistory () {
        //     this.$refs.AuditHistoryRef.auditHistory()
        // },
        //获取基本信息数据  编辑页面
        getInfo () {
            const params = {
                billId: this.billid,
                depositType: this.depositType
            }
            request.PccSetCorresData(params).then(res=>{
                // res.businessTypeKey = String(res.businessTypeKey)
                this.formData = res
                this.checkedBox = res.advanceChargeAmount === 0 ? false : true
                this.checkPerson = res.rushPersonalBorrowingAmount === 0 ? false : true
                this.shareFontColor()
                let data = res
                if (data.redStatus == '3') {
                // 如果是3,说明进入该单据是红单进入到编辑页
                    data.businessTypeKey = this.businessTypeList.find(
                        item => item.value === data.businessTypeKey
                    ).key
                    data.currency = this.currencyForm.find(
                        x => x.value == data.currencyId
                    ).label
                    this.formData = data
                    this.isRedSingle = true
                } else {
                    this.formData = data
                }
            })
            request.PccSetGetDtlListData(params).then(res=>{
                res.forEach(item=>{
                    item.uuid = getUuid()
                    item.materialClassName = item.topClassName
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.parentId = item.uuid
                    })
                })
                this.acceptanceData = res
            })
            //获取服务明细
            request.PccSetGetFreightDtlData(params).then(res=>{
                this.rentalBusinessCopy = res
            })
            // 获取保证金
            request.PccSetDepositIdData(params).then(res=>{
                this.changeKouTable = res.filter(item => item.depositType === 1)
                this.changeReturnTable = res.filter(item => item.depositType === 2)
            })
        },
        //变更历史查询
        getChangeHistory () {
            const params = {
                billId: this.billid,
                billType: 6095
            }
            request.PccgetAuditHistoryInfo(params).then(()=>{
                // this.changeHistoryTable = res
            })
        },
        onAmount  (row) {
            let obj = this.oldConfigPlan.find(x=>x.planDtlId === row.planDtlId)
            if(obj) {
                var oldQuantity = obj.quantity
            }
            if(row.settlePrice > oldQuantity ) {
                this.clientPop(
                    'err',
                    '不能大于未验收数量',
                )
                row.quantity = +oldQuantity
            }
            row.taxExcludedAmount = row.quantity * row.price / (row.quantity + row.unsettleQuantity)
            this.onUpCollect()
        },
        //费用合计 = 明细获取金额向上汇总
        onUpCollect () {
            this.formData.planLease.totalCost = null
        },
        //判断当前状态是否已修改   结算明细和服务费用
        curStateChange (row) {
            this.currentRowPlan = row
            if(row.changeType != -1) {
                if(this.fake) {
                    this.currentRowPlan.changeType = 1
                }else{
                    this.currentRowPlan.changeType = 2
                }
            }

        },
        //如果是-1就隐藏
        tableRowClass ({ row }) {
            if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //判断结算明细结算单价不能超过验收单价
        onQuantity  (row) {
            let settlePrice = row.settlePrice
            if(row.settlePrice > row.price ) {
                this.clientPop(
                    'err',
                    '结算单价不能超过验收单价',
                )
                row.price = +settlePrice
            }
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //弹窗返还保证金
        boxHandelReturn () {      //获取返还保证金弹框
            let obj = {
                'amount': 0,
                'amountBqm': 0,
                'amountSqm': 0,
                'billId': this.$route.query.billid,
                'changeType': 0,
                'depositType': 2,
                'dtlId': '',
                'remarks': '',
                'returnDepositId': '',
                'returnDepositName': ''
            }
            this.changeReturnTable.push(obj)
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnoversettle/BuySettle/selectDeposit', // 获取返还保证金弹窗
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({ 'keyWord': '', 'sourceId': '1' }),
                Title: '选择返还保证金数据' // 标题
            }).then(val => {
                obj.amountSqm = val[0].amountBqm - val[0].amount
                // }
            })
        },
        //单个删除返还保证金
        handleDeleteRental (row, $index) {
            console.log(row)
            if(row.returnDepositId) {
                this.$set(this.changeReturnTable[$index], 'changeState', -1)
                this.changeReturnTable.splice( $index, 1)
            }else{
                this.changeReturnTable.splice( $index, 1)
            }
        },
        //点击返还保证金删除弹窗
        handleChangeReturn () {
            const length = this.changeReturnSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.deleteRentalReturn
                )
            }

        },
        //批量删除返还保证金
        deleteRentalReturn  () {
            console.log(111111111)
            if (this.changeReturnSelect.length > 0) {
                this.changeReturnSelect.forEach(item=>{
                    if(item.returnDepositId) {
                        this.$set(item, 'changeState', -1)
                        this.changeReturnTable.map((x, i)=>{
                            if(x == item) {
                                this.changeReturnTable.splice(i, 1)
                            }
                        })
                        this.$refs.attach.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.changeReturnTable.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.changeReturnSelect[i - 1] === localArr[j]) {
                                    this.changeReturnTable.splice(i - 1, 1)
                                }
                                if(this.changeReturnSelect[i - 1] === localArr[j]) {
                                    this.changeReturnTable.splice(i - 1, 1)
                                }
                            }
                        }
                        this.$refs.attach.clearSelection()
                    }
                })
            }
        },
        //获取返还保证金数据
        changeHistoryTableSelect (selection) {
            this.changeReturnSelect = selection
        },
        BoxHandelkou () {     //暂扣保证金弹框
            let obj = {
                'amount': 0,
                'amountBqm': 0,
                'amountSqm': 0,
                'billtId': this.$route.query.billid,
                'changeType': 0,
                'depositType': 1,
                'dtlId': '',
                'remarks': '',
                'returnDepositId': '',
                'returnDepositName': ''
            }
            this.changeKouTable.push(obj)
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnoversettle/BuySettle/selectDeposit', // 获取暂扣保证金弹窗
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({ 'keyWord': '', 'sourceId': '1' }),  //待修改参数
                Title: '选择暂扣保证金数据' // 标题
            }).then(val => {
                obj.returnDepositName = val[0].returnDepositName
                obj.amountBqm = val[0].amountBqm
                obj.amountSqm = val[0].amountBqm + val[0].amount
            })
        },
        //点击暂扣保证金删除弹窗
        handleChangekou () {
            const length = this.changeKouSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.deleteRentalKou
                )
            }

        },
        //获取暂扣保证金数据
        KouTableSelect (selection) {
            this.changeKouSelect = selection
        },
        //批量删除暂扣保证金
        deleteRentalKou  () {
            if (this.changeKouSelect.length > 0) {
                this.changeKouSelect.forEach(item=>{
                    if(item.returnDepositId) {
                        this.$set(item, 'changeState', -1)
                        this.changeKouTable.map((x, i)=>{
                            if(x == item) {
                                this.changeKouTable.splice(i, 1)
                            }
                        })
                        this.$refs.attach.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.changeKouTable.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.changeKouSelect[i - 1] === localArr[j]) {
                                    this.changeKouTable.splice(i - 1, 1)
                                }
                                if(this.changeKouSelect[i - 1] === localArr[j]) {
                                    this.changeKouTable.splice(i - 1, 1)
                                }
                            }
                        }
                        this.$refs.attach.clearSelection()
                    }
                })
            }
        },
        //单个删除暂扣保证金
        handleDeleteKou (row, $index) {
            console.log(row)
            if(row.returnDepositId) {
                this.$set(this.changeKouTable[$index], 'changeState', -1)
                this.changeKouTable.splice( $index, 1)
            }else{
                this.changeKouTable.splice( $index, 1)
            }
        },
        //弹窗选择结算明细
        settleOrgChange () {
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnover/acceptance/selectSettleDtl', // 获取选择结算明细
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({  'businessTypeKey': '1',
                    'keyWord': '',
                    'parentId': '0' }),
                Title: '选择结算单位数据' // 标题
            }).then(val => {
                this.formData.settleOrg = val[0].settleOrgName
            })
        },
        //弹窗选择结算点击选择物资  结算明细
        selectEquip () {
            let obj =
                {
                    'children': [
                        {
                            'billId': this.$route.query.billid,
                            'changeType': 0,
                            'difference': 0,
                            'dtlId': '',
                            'materialClassId': '',
                            'materialClassName': '',
                            'materialId': '',
                            'materialName': '',
                            'price': 0,
                            'quantity': 0,
                            'settlePrice': 0,
                            'spec': '',
                            'taxAmountDifference': 0,
                            'taxExcludedAmount': 0,
                            'texture': '',
                            'unit': '',
                            'uuid': getUuid(),
                            'unsettleQuantity': 0
                        }
                    ],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': getUuid(),
                }
            this.acceptanceData.push(obj)
            console.log(this.acceptanceData, 'this.acceptanceData')
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnover/acceptance/selectSettleDtl', // 获取选择结算明细
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({  'businessTypeKey': '1',
                    'keyWord': '',
                    'parentId': '0' }),
                Title: '选择结算明细数据' // 标题
            }).then(val => {
                // alert(JSON.stringify(val))
                obj.children[0].materialClassName = val[0].materialClassName
                obj.children[0].materialName = val[0].materialName
                obj.children[0].spec = val[0].spec
                obj.children[0].settlePrice = val[0].acceptPrice
                obj.children[0].texture = val[0].texture
                obj.children[0].unit = val[0].unit
                obj.children[0].quantity = val[0].acceptQantity
                obj.children[0].taxExcludedAmount = val[0].acceptAmount
            //     this.setSelectedInfo(val)
            //     // 客户端弹窗预览结果
            //     // 参数依次为: 打开页面地址、标题、回调函数
            //     openAppClient('/showSelectedData', '选择结果', function () {
            //         // alert('关闭后回调')
            //     })
            })
        },
        //删除单条结算明细数据
        handleDeletePlanList (row, $index) {
            if(row.billId) {
                this.$set(this.acceptanceData[$index], 'changeState', -1)
                this.acceptanceData.splice( $index, 1)
            }else{
                this.acceptanceData.splice( $index, 1)
            }
        },
        //点击结算明细删除弹窗
        deletePlanList () {
            const length = this.acceptanceCkeck.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除后将删除对应的结算明细。删除的数据可以在【回收站】还原或彻底删除。`,
                    this.deletePlanListTo
                )
            }

        },
        //获取勾选的结算明细数据
        acceptanceSelect (selection) {
            this.acceptanceCkeck = selection
        },
        deletePlanListTo () {
            if (this.acceptanceCkeck.length > 0) {
                this.acceptanceCkeck.forEach(item=>{
                    if(item.materialClassId) {
                        this.$set(item, 'changeState', -1)
                        this.acceptanceData.map((x, i)=>{
                            if(x == item) {
                                this.acceptanceData.splice(i, 1)
                            }
                        })
                        this.$refs.changeDetail.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.acceptanceData.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.acceptanceCkeck[i - 1] === localArr[j]) {
                                    this.acceptanceData.splice(i - 1, 1)
                                }
                                if(this.acceptanceCkeck[i - 1] === localArr[j]) {
                                    this.acceptanceData.splice(i - 1, 1)
                                }
                            }
                        }
                        this.$refs.changeDetail.clearSelection()
                    }
                })
            }
        },
        //服务费用新增行
        newRentalAdd () {
            if(this.acceptanceData[0].children[0].materialName !== null || this.acceptanceData[0].children[0].materialName !== '') {
                let obj = {
                    'amount': 0,
                    'billId': this.$route.query.billid,
                    'changeType': 0,
                    'contractDtlId': '',
                    'contractDtlName': '',
                    'contractId': '',
                    'contractNumber': '',
                    'dtlId': '',
                    'price': 0,
                    'quantity': 0,
                    'settlementUnitId': '',
                    'settlementUnitName': '',
                    'taxAmount': 0,
                    'taxRate': 0,
                    'totalAmount': 0
                }
                this.rentalBusinessCopy.push(obj)
            }else{
                this.$message.warning('请先填写选择结算明细相关信息')
            }
        },
        //弹窗选择服务费用
        newRentalBusiness () {
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnoversettle/BuySettle/selectDeposit', // 获取选择服务费用
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '选择返还保证金数据' // 标题
            }).then(val => {
                this.yunshuAmount.quantity = val[0].quantity      //待修改数据
                this.yunshuAmount.price = val[0].price
                this.yunshuAmount.amount =  this.yunshuAmount.quantity * this.yunshuAmount.price
                console.log(val)
                // this.selectConfirm(val)
            })
        },
        //选择设备确认
        selectConfirm (data) {
            let obj  = {
                ...this.current,
                ...data[0]
            }
            this.$set(this.rentalBusiness, this.index, obj)
            if(!data) return false
            this.selectEquipVisible = false
        },
        //获取服务费用表格的选择项
        rentalTableSelect (selection) {
            this.rentalBusinesscheck = selection
        },
        handleDeleteBusiness (row, $index) {
            if(row.settlementUnitId) {
                this.$set(this.rentalBusinessCopy[$index], 'changeState', -1)
                this.rentalBusinessCopy.splice( $index, 1)
            }else{
                this.rentalBusinessCopy.splice( $index, 1)
            }
        },
        //点击服务费用删除弹窗
        deleteRentalBusiness () {
            const length = this.rentalBusinesscheck.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.deleteRental
                )
            }

        },
        //批量删除服务费用
        deleteRental () {
            if (this.rentalBusinesscheck.length > 0) {
                this.rentalBusinesscheck.forEach(item=>{
                    if(item.settlementUnitId) {
                        this.$set(item, 'changeState', -1)
                        this.rentalBusinessCopy.map((x, i)=>{
                            if(x == item) {
                                this.rentalBusinessCopy.splice(i, 1)
                            }
                        })
                        this.$refs.recommendedLessor.clearSelection()
                    }else{
                        const localArr = []
                        localArr.push(item)
                        for(let i = this.rentalBusinessCopy.length; i > 0; i--) {
                            for(let j = 0; j < localArr.length; j++) {
                                if(this.rentalBusinesscheck[i - 1] === localArr[j]) {
                                    this.rentalBusinessCopy.splice(i - 1, 1)
                                }
                                if(this.rentalBusinesscheck[i - 1] === localArr[j]) {
                                    this.rentalBusinessCopy.splice(i - 1, 1)
                                }
                            }
                        }
                        this.$refs.recommendedLessor.clearSelection()
                    }
                })
            }
        },
        handleDeleteHistory (row) {
            let billids = [row.billId]
            request.leaseDelete(billids).then(()=>{
                this.init()
                this.clientPop('suc', '删除成功')
                this.$refs.changeHistorySelect.clearSelection()
            })
        },
        //删除草稿状态的变更历史
        handleChangeHistory () {
            const length = this.changeHistorySelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.changeHistorySelect.forEach(item=>{
                    if(item.state !== 0) {
                        this.clientPop(
                            'info',
                            '只有草稿状态才可以删除！',
                        )
                        this.$refs.changeHistorySelect.clearSelection()
                    }else{
                        this.clientPop(
                            'info',
                            `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                            this.deleteChangeHistory
                        )
                    }
                })
            }
        },
        //批量或单独删除变更历史
        deleteChangeHistory () {
            let billids = []
            this.changeHistorySelect.forEach(item=>{
                console.log(item.state)
                if(item.state === 0) {
                    billids.push(item.billId)
                    request.leaseDelete(billids).then(()=>{
                        this.init()
                        this.clientPop('suc', '删除成功')
                        this.$refs.changeHistorySelect.clearSelection()
                    })
                }
            })
        },
        //结算明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.acceptanceData.forEach((item, index)=>{
                    console.log(item)
                    console.log(index)
                    if(item.changeType !== -1) {
                        if(item.children[0].taxExcludedAmount == null || item.children[0].taxExcludedAmount == '') {
                            let str = `请填写第 ${index + 1} 行的（物资名称）`
                            this.errorMsg.push(str)
                        }
                        // if( item.price == '' || item.price == null) {
                        //     let str = `请填写第 ${index + 1} 行的（验收单价（元））`
                        //     this.errorMsg.push(str)
                        // }
                        // if(item.unsettleQuantity == null || item.unsettleQuantity == '') {
                        //     let str = `请填写第 ${index + 1} 行的（未结算数量）`
                        //     this.errorMsg.push(str)
                        // }
                        // if(item.settlePrice == null || item.settlePrice == '') {
                        //     let str = `请填写第 ${index + 1} 行的（结算单价（元））`
                        //     this.errorMsg.push(str)
                        // }
                        // if(item.taxAmountDifference == '' || item.taxAmountDifference == null) {
                        //     let str = `请填写第 ${index + 1} 行的（税额差额（元））`
                        //     this.errorMsg.push(str)
                        // }
                        // if(item.difference == '' || item.difference == null) {
                        //     let str = `请填写第 ${index + 1} 行的（差额（元））`
                        //     this.errorMsg.push(str)
                        // }
                    }

                })
                if(this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                }else{
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                request.PccSetCorresData(this.formData).then(res=>{
                    console.log(res, '修改基础數據信息111')
                    this.verifyTable().then(()=>{
                        request.PccSetupdateDtldData(this.acceptanceData).then(ress=>{  //更新采购结算明细
                            console.log(ress, '修改基础结算信息111')
                            request.PccSetFreightDtltData(this.rentalBusinessCopy).then(resD=>{   //更新服务费用
                                console.log(resD, '修改基础服务信息111')
                                request.PccSetSelectDepositData([...this.changeKouTable, ...this.changeReturnTable]).then(resM =>{
                                    console.log(resM, '修改保证金111')
                                }).catch(err=>{
                                    this.setError('attach')
                                    reject(err)
                                })
                                resolve()
                            }).catch(err=>{
                                this.setError('recommendedLessor')
                                reject(err)
                            })
                        }).catch(err=>{
                            this.setError('changeDetail')
                            reject(err)
                        })
                    }).catch(err=>{
                        this.setError('changeDetail')
                        this.scorllError()
                        reject(err)
                    })

                }).catch(err=>{
                    console.log(err)
                    this.setError('baseInfo')
                    reject(err)

                })
            })
        },
        //删除采购结算
        deleteBills () {
            // let billids = [this.billid]
            const params = {
                billId: this.billid,
            }
            console.log(params)
            request.PccSetDeleteData(params).then(()=>{
                // console.log(res, 'kkkkkkkkkk')
                this.clientPop('suc', '删除成功', this.handleClose)
            })
        },
        //保存全部数据
        saveAll () {
            this.errorList = []
            Promise.all([
                this.updateBaseInfo(),
            ])
                .then(() => {
                    this.clientPop('suc', '保存成功')
                })
                .catch(()=> {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //保存并提交
        submitCommit () {
            if(this.acceptanceData.length === 0) {
                let str = '结算明细不能空！'
                this.errorMsg.push(str)
                this.setError('changeDetail')
                this.scorllError()
                return
            }
            Promise.all([
                this.updateBaseInfo(),
                //this.updateBusiness()
            ])
                .then(() => {
                    commit(this.auditParams).then(()=>{
                        this.clientPop('suc', '保存并提交成功', ()=>{ this.$router.push('/PccSetList') })
                        this.init()
                    }).catch(()=>{
                        this.clientPop('err', '提交失败！')
                    })
                })
                .catch(()=> {
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        /*审核相关操作*/
        //获取流程按钮显示状态
        PccSetgetCurrentUnitInfo () {
            PccSetgetCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            //客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', ()=>{ this.$router.push('/PccSetList') })
                    this.init()
                })
            })
        },
        async exas (arg) {
            if (arg === 'audit') {
                this.setAuditParams(this.auditParams)
                // 客户端弹窗弹出本地页面
                this.setSelectedInfo(this.auditParams)
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    audit(auditParams).then(() => {
                        this.init()
                        this.clientPop('suc', '审核成功')
                    })
                })
            } else if (arg === 'undoAudit') {
                undoworkt(this.auditParams).then(() => {
                    this.clientPop('suc', '撤回成功')
                    this.init()
                })
            } else if (arg === 'submitCommit') {
                this.submitCommit()  //保存并提交
            } else if (arg === 'submit') {
                this.saveAll()   //保存
            } else if (arg === 'nullify') {
                this.setAuditParams(this.nullifyParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/nullifyDialog', '单据作废原因', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    nullify(auditParams).then(() => {
                        this.clientPop('suc', '作废成功')
                        this.init()
                    })
                })
            } else if (arg === 'deleteData') {
                this.clientPop(
                    'info',
                    '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                    this.deleteBills
                )
            }
        },
        //取消
        handleClose () {
            this.$router.replace('/PccSetList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //冲红单
        redHandel () {
            const params = {
                billId: this.billid
            }
            request.PccSetNewDataInfo({
                // ...this.formData,
                // businessTypeKey: parseInt(this.formData.businessTypeKey),
                // taxRate: parseInt(this.formData.taxRate),
                // checkedBox: this.checkedBox
            }).then(res=>{
                console.log(res)
                request.PccinitRedInfo(params).then(res => {
                    this.clientPop('info', '保存成功!是否进行下一步操作？', ()=>{
                        this.$router.push({
                            path: '/NewPlanDetail',
                            query: {
                                billid: res,
                                name: 'changeDetail'
                            }
                        })
                    },
                    null,
                    this.handleClose
                    )
                    // this.$router.replace({
                    //     name: 'redData',
                    //     query: { redStatus: this.redStatus, billId: this.billid },
                    //     params: {
                    //         redData: res,
                    //     },
                    // })
                    console.log(res)
                })

            })
        },
        //冲销对象
        handelChange () {
            let ids = []
            let params = []
            params.push(this.formData.billid)
            selectDataClient({
                SelectServiceToken: '/facilityconnect/lease/receive/plan/contract/receive', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify(params),    // 接口参数(name为模拟参数)
                Title: '选择冲销对象' // 标题
            }).then(val => {
                this.formData.reversalObjectName = val[0].reversalObjectName
            })
        },
        //获取借支人员
        getSigningName ()  {
            selectDataClient({
                SelectServiceToken: '/hr/user/getUserUnderOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({ 'orgId': this.formData.orgId }),    // 接口参数
                Title: '选择借支人员' // 标题
            }).then(val => {
                this.formData.borrower = val[0].userName
            })
        }
    },
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
::v-deep input.el-input__inner {
    border: 0;
}
</style>
